package com.xlhj.yucloud.controller;

import cn.hutool.core.map.MapUtil;
import com.xlhj.yucloud.common.ResultData;
import com.xlhj.yucloud.entity.SysMenuInfo;
import com.xlhj.yucloud.entity.SysUserInfo;
import com.xlhj.yucloud.service.SysMenuInfoService;
import com.xlhj.yucloud.service.SysRoleInfoService;
import com.xlhj.yucloud.service.SysUserInfoService;
import com.xlhj.yucloud.web.model.LoginBody;
import com.xlhj.yucloud.web.model.RouterMenu;
import com.xlhj.yucloud.web.service.LoginService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.util.List;
import java.util.Set;

/**
 * @author: liucaijing
 * @description: 用户登录
 * @date: 2021/9/10 14:23
 */
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class SysLoginController {
    
    private final LoginService loginService;
    private final SysUserInfoService userInfoService;
    private final SysRoleInfoService roleInfoService;
    private final SysMenuInfoService menuInfoService;

    @PostMapping("/login")
    public ResultData login(@RequestBody LoginBody loginBody) {
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword());
        return ResultData.success().data(MapUtil.builder().put("token", token).build());
    }

    /**
     * 获取用户信息
     * @param principal
     * @return
     */
    @GetMapping("/info")
    public ResultData getInfo(Principal principal) {
        String name = principal.getName();
        SysUserInfo userInfo = userInfoService.findUserByUserName(name);
        Set<String> roleList = roleInfoService.getRolePermsByUserId(userInfo.getId());
        return ResultData.success().data(MapUtil.builder()
                .put("id", userInfo.getId())
                .put("name", userInfo.getUserName())
                .put("avatar", userInfo.getAvatar())
                .put("roles", roleList)
                .put("introduction", "I am a super administrator").build());
    }

    @GetMapping("/getRoutes")
    public ResultData getRoutes() {
        SysUserInfo userInfo = loginService.getUserInfo();
        List<SysMenuInfo> menuInfos = menuInfoService.selectMenuTreeByUserId(userInfo.getId());
        List<RouterMenu> routerMenus = menuInfoService.buildMenus(menuInfos);
        return ResultData.success().data(routerMenus);
    }

    @PostMapping("/logout")
    public ResultData logout() {
        return ResultData.success();
    }
}
